//
//  SMAlbumViewController.m
//  cherryproduct
//
//  Created by zou shigang on 14/8/30.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "SMAlbumViewController.h"


@interface SMAlbumViewController ()


@end

@implementation SMAlbumViewController

- (UICollectionView*)album_local
{
    if (_album_local==nil) {
        UICollectionViewFlowLayout * layout= [[UICollectionViewFlowLayout alloc] init];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        [layout setItemSize:CGSizeMake(79, 79)]; //设置每个cell显示数据的宽和高必须
        layout.sectionInset = UIEdgeInsetsMake(5, 0, 0, 0);
        layout.minimumLineSpacing=1;
        layout.minimumInteritemSpacing=1;
        layout.footerReferenceSize=CGSizeMake(self.view.frame.size.width, 50);
        
        CGFloat f_height = 20;
        if ([[UIDevice currentDevice].systemVersion doubleValue] < 7.0) {
            f_height=0;
        }
        _album_local = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44+f_height, self.view.frame.size.width, self.view.frame.size.height-44-f_height) collectionViewLayout:layout];
        _album_local.backgroundColor=[UIColor whiteColor];
        _album_local.delegate=self;
        _album_local.dataSource=self;
        [_album_local registerClass:[AlbumCell class] forCellWithReuseIdentifier:CELLID];
        //[_album_local registerClass:[ALbumFooter class] forCellWithReuseIdentifier:CELLID_FOOTET];
        [_album_local registerClass:[ALbumFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:CELLID_FOOTET];
        [self.view addSubview:_album_local];
    }
    return _album_local;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"选择照片"];
    [self addNavBarButton:RIGHT_SELECT_PHOTO];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    [self getAssert];
}

- (void)backButtonAction:(UIButton*) sender
{
    if (self.block_dismiss) {
        self.block_dismiss(0);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc
{
    self.album_local.delegate=nil;
    self.album_local.dataSource=nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)submentbuttondown:(UIButton*)button
{
    NSLog(@"ok");
    if ([self.array_select count] <= 0) {
        [self showAlertView:@"温馨提示" subtitle:@"请选择图片!"];
    } else {
        if (self.block_dismiss) {
            self.block_dismiss(1);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark GetData
//- (NSMutableArray*)array_assert
//{
//    if (_array_assert==nil) {
//        _array_assert =[[NSMutableArray alloc] initWithCapacity:8];
//    }
//    return _array_assert;
//}

//- (NSMutableArray*)array_select
//{
//    if (_array_select==nil) {
//        _array_select =[[NSMutableArray alloc] initWithCapacity:8];
//    }
//    return _array_select;
//}


- (void)getAssert
{
//    if (assetsLibrary==nil) {
//        assetsLibrary = [[ALAssetsLibrary alloc] init];
//    }
    if (self.m_b_have_load_img) {//已经加载过照片,防止重复加载
        [self.album_local reloadData];
        return;
    }
    
    __block SMAlbumViewController * strongSelf = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            @autoreleasepool {
                [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    if (result == nil)
                    {
                        return;
                    }
                    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                        [strongSelf.array_assert addObject:result];
                    }
                }];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"count:%lu", (unsigned long)[strongSelf.array_assert count]);
                [strongSelf.album_local reloadData];
            });
        } failureBlock:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"程序无访问相册权限(设置>隐私>照片,请进行设置)" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alert_show show];
            });
        }];
    });
}

#pragma mark -
#pragma mark UICollectionViewDataSource, UICollectionViewDelegate

//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
//                       layout:(UICollectionViewLayout *)collectionViewLayout
//       insetForSectionAtIndex:(NSInteger)section
//{
//    UIEdgeInsets top = {10,0,15,0};
//    return top;
//}

//-(CGSize)collectionView:(UICollectionView *)collectionView
//                 layout:(UICollectionViewLayout *)collectionViewLayout
// sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//    return CGSizeMake(78, 78);
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    return [self.array_assert count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    AlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID forIndexPath:indexPath];
    
    // load the image for this cell
    ALAsset * object = [self.array_assert objectAtIndex:indexPath.row];
    cell.image_thumb.image = [UIImage imageWithCGImage:object.thumbnail];
    if ([self.array_select indexOfObject:object] == NSNotFound) {
        cell.select_image.highlighted=NO;
    } else {
        cell.select_image.highlighted=YES;
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    ALbumFooter *footer = nil;
    if([kind isEqual:UICollectionElementKindSectionFooter]){
        footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                    withReuseIdentifier:@"ALbumFooter"
                                                           forIndexPath:indexPath];
        //if ([self.array_assert count]>16) {
        if (self.array_assert) {
            footer.label_num.text = [NSString stringWithFormat:@"%lu张照片", (unsigned long)[self.array_assert count]];
        }
        //}
    } else if([kind isEqual:UICollectionElementKindSectionHeader]) {
        ALbumHeader * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                  withReuseIdentifier:@"ALbumHeader"
                                                                         forIndexPath:indexPath];
        return header;
    }
    return footer;
}

//- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
//{
//    AlbumCell * cell=(AlbumCell*)[collectionView cellForItemAtIndexPath:indexPath];
//    cell.select_image.highlighted=NO;
//    return YES;
//}
//- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath;
//{
//    AlbumCell * cell=(AlbumCell*)[collectionView cellForItemAtIndexPath:indexPath];
//    cell.select_image.highlighted=YES;
//}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    NSLog(@"select index:%d", indexPath.row);
    ALAsset * object = [self.array_assert objectAtIndex:indexPath.row];
    if ([self.array_select indexOfObject:object] == NSNotFound) {
        //sub
        if ([self.array_select count] >= 9) {
            [self showAlertView:@"温馨提示" subtitle:@"最多上传9张图片!"];
        } else {
            [self.array_select addObject:object];
        }
    } else {
        //add
        [self.array_select removeObject:object];
    }
    [collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetailImage"])
    {
        //        NSIndexPath *selectedIndexPath = [[self.album_local indexPathsForSelectedItems] objectAtIndex:0];
        
        //        SMImageDetailViewController *detailViewController = [segue destinationViewController];
        //        [detailViewController setAssertImage:self.array_assert showIndex:selectedIndexPath.row];
    }
}

@end









@implementation AlbumCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在此添加
        // 初始化时加载collectionCell.xib文件
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"AlbumCell" owner:self options: nil];
        // 如果路径不存在，return nil
        if(arrayOfViews.count < 1){return nil;}
        // 如果xib中view不属于UICollectionViewCell类，return nil
        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]){
            return nil;
        }
        // 加载nib
        self = [arrayOfViews objectAtIndex:0];
    }
    return self;
}

@end

@implementation ALbumFooter

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在此添加
        // 初始化时加载collectionCell.xib文件
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"ALbumFooter" owner:self options: nil];
        // 如果路径不存在，return nil
        if(arrayOfViews.count < 1){return nil;}
        // 如果xib中view不属于UICollectionViewCell类，return nil
        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionReusableView class]]){
            return nil;
        }
        // 加载nib
        self = [arrayOfViews objectAtIndex:0];
    }
    return self;
}

@end

@implementation ALbumHeader



@end









